
package com.be.beadmin.product.impl;

import com.be.beadmin.basicData.entity.User;
import com.be.beadmin.basicData.repository.UserRepository;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.design.entity.StandFileInfo;
import com.be.beadmin.product.dto.input.ErrorReportByWoPage;
import com.be.beadmin.product.dto.input.ErrorReportDto;
import com.be.beadmin.product.dto.input.ErrorReportSimpDto;
import com.be.beadmin.product.dto.output.ErrorPriorityEx;
import com.be.beadmin.product.dto.output.ErrorReportEx;
import com.be.beadmin.product.dto.output.ErrorReportForExportEx;
import com.be.beadmin.product.dto.output.ErrorTypeEx;
import com.be.beadmin.product.entity.ErrorReport;
import com.be.beadmin.product.entity.ErrorReportFileInfo;
import com.be.beadmin.product.entity.ErrorReport_;
import com.be.beadmin.product.entity.ProductManufactInfor;
import com.be.beadmin.product.mapper.ErrorReportMapper;
import com.be.beadmin.product.mapper.ErrorReportMapperEx;
import com.be.beadmin.product.repository.ErrorReportFileInfoRepository;
import com.be.beadmin.product.repository.ErrorReportRepository;
import com.be.beadmin.product.repository.ProductManufactInforRepository;
import com.be.beadmin.product.service.ErrorReportService;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.service.entity.DictType;
import com.be.beadmin.service.entity.NotifyInfo;
import com.be.beadmin.service.entity.NotifyTemplateInfo;
import com.be.beadmin.service.impl.MinioService;
import com.be.beadmin.service.impl.WebSocketNotifyService;
import com.be.beadmin.service.repository.DictTypeRepository;
import com.be.beadmin.service.repository.NotifyInfoRepository;
import com.be.beadmin.service.repository.NotifyTemplateInfoRepository;
import com.be.beadmin.service.service.DictDataService;
import com.be.beadmin.service.service.NotifyTemplateInfoService;
import com.be.beadmin.service.service.SerialNumberService;
import com.sun.org.apache.xpath.internal.operations.Mult;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
* @description 服务实现
* @author ljh
* @date 2023-04-21
**/
@Service
@RequiredArgsConstructor
public class ErrorReportServiceImpl implements ErrorReportService {

    @Autowired
    private  ErrorReportRepository errorReportRepository;
    @Autowired
    private  ErrorReportMapper errorReportMapper;
    @Autowired
    private  ErrorReportMapperEx errorReportExMapper;

    @Autowired
    private ProductManufactInforRepository productManufactInforRepository;

    @Autowired
    private DictTypeRepository dictTypeRepository;

    @Autowired
    private DictDataService dictDataService;

    @Autowired
    private SerialNumberService serialNumberService;

    @Autowired
    private MinioService minioService;

    MinioUtil minioUtil = new MinioUtil();

    @Autowired
    UserRepository userRepository;

    @Autowired
    private NotifyTemplateInfoService notifyTemplateInfoService;

    @Autowired
    private NotifyTemplateInfoRepository notifyTemplateInfoRepository;

    @Autowired
    private NotifyInfoRepository notifyInfoRepository;

    @Autowired
    private ErrorReportFileInfoRepository errorReportFileInfoRepository;

    @Override
    public Page<ErrorReportEx> getErrorReportByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<ErrorReport> page = errorReportRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(ErrorReport_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(ErrorReport_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<ErrorReportEx> page1 = page.map(errorReportExMapper::toEntity);
            return page1;
    }

    @Override
    public Page<ErrorReportEx> getErrorReportByPageAndWo(ErrorReportByWoPage errorReportByWoPage) {
        PageEntity pageEntity = errorReportByWoPage.getPageEntity();
        String wo = errorReportByWoPage.getWo();
        if (wo == null) throw new BeadminException("需要指定工单号");
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<ErrorReport> page = errorReportRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(ErrorReport_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate pre3 = criteriaBuilder.equal(root.get(ErrorReport_.wo), wo); //过滤为Wo
                    list.add(pre3);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(ErrorReport_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<ErrorReportEx> page1 = page.map(errorReportExMapper::toEntity);
        return page1;
    }

    @Override
    public List<ErrorPriorityEx> getAllErrorPriority() {
        DictType dictType = dictTypeRepository.findDictTypeByDictName("异常优先级");
        HashMap<String,String> map = dictDataService.getDictDataMapByDictTypeId(dictType);
        List<ErrorPriorityEx> errorPriorityExList = new ArrayList<>();
        map.forEach((key,value) -> {
            ErrorPriorityEx errorPriorityEx = new ErrorPriorityEx();
            errorPriorityEx.setPriority(key);
            errorPriorityEx.setPriorityDes(value);
            errorPriorityExList.add(errorPriorityEx);
        });
        return errorPriorityExList;
    }

    @Override
    public List<ErrorTypeEx> getAllErrorType() {
        DictType dictType = dictTypeRepository.findDictTypeByDictName("异常类型");
        HashMap<String,String> map = dictDataService.getDictDataMapByDictTypeId(dictType);
        List<ErrorTypeEx> errorTypeExList = new ArrayList<>();
        map.forEach((key,value) -> {
            ErrorTypeEx errorTypeEx = new ErrorTypeEx();
            errorTypeEx.setErrorType(key);
            errorTypeEx.setErrorTypeDes(value);
            errorTypeExList.add(errorTypeEx);
        });
        return errorTypeExList;
    }

    @Transactional
    @Override
    public void addErrorReport2(String workOrderInforId, String wo, String taskId, String errorType, String priority, String handlingMan, Date deadLine, String errorDes, String operator, MultipartFile[] multipartFiles, String bucketName,String projectName,Float workHour) throws Exception {
        ErrorReportDto errorReportDto = new ErrorReportDto();

        errorReportDto.setWorkOrderInforId(workOrderInforId);
        errorReportDto.setWo(wo);
        errorReportDto.setTaskId(taskId);
        errorReportDto.setErrorType(errorType);
        errorReportDto.setPriority(priority);
        errorReportDto.setHandlingMan(handlingMan);
        errorReportDto.setDeadLine(deadLine);
        errorReportDto.setErrorDes(errorDes);
        errorReportDto.setOperator(operator);
        errorReportDto.setPushStatus(1);// 已推送
        errorReportDto.setHandleStatus(0); //待处理
        errorReportDto.setProjectName(projectName);
        errorReportDto.setWorkHour(workHour);

        if(taskId!=null&& !taskId.equals("null")){
            ProductManufactInfor productManufactInfor = productManufactInforRepository.findProductManufactInforByIdAndDelete(taskId,0);

            errorReportDto.setProductCode(productManufactInfor.getBatchProductCode());
            errorReportDto.setProcessCode(productManufactInfor.getProcessCode());
            errorReportDto.setProcessName(productManufactInfor.getProcessName());
            errorReportDto.setProcessSequence(String.valueOf(productManufactInfor.getSequence()));
        }

        errorReportDto.setBucketName(bucketName);

        ErrorReport errorReport = errorReportRepository.save(errorReportMapper.toEntity(errorReportDto));

        for(MultipartFile multipartFile:multipartFiles){
            //附件相关
            if(multipartFile!=null) {

                ErrorReportFileInfo errorReportFileInfo =new ErrorReportFileInfo();

                errorReportFileInfo.setFileCode(serialNumberService.getNextSnByCode("FileCode"));
                errorReportFileInfo.setFileName( multipartFile.getOriginalFilename());
                errorReportFileInfo.setBucketName(bucketName);
                String uploadFileName = errorReportFileInfo.getFileCode()+"+"+errorReportFileInfo.getFileName();
                String preview_url = minioUtil.uploadFile2(multipartFile,uploadFileName,bucketName);
                errorReportFileInfo.setAttachmentUrl(preview_url);

                errorReportFileInfo.setErrorReportId(errorReport.getId());

                errorReportFileInfoRepository.save(errorReportFileInfo);
            }
        }


        //-----------------------------------------------------------------------
        // 异常填报人 发送 异常待处理 待办给  异常处理人
        NotifyInfo notifyInfo =new NotifyInfo();
        notifyInfo.setModuleName("工作平台");
        notifyInfo.setFuncName("异常发布");

        if(wo==null) wo="-";
        String projectName2= "-";
        if(projectName!=null) projectName2=projectName;


        notifyInfo.setNotifyDesc("项目名称为["+projectName2+"],工单号为["+wo+"],出现["+errorType+"]--异常需要处理");
        notifyInfo.setNotifyType("待办");
        notifyInfo.setSenderName(errorReport.getOperator());
        notifyInfo.setSendTime(errorReport.getCreateTime());
        notifyInfo = notifyInfoRepository.save(notifyInfo);

        notifyTemplateInfoService.sendNotify(notifyInfo,-2,handlingMan,null);

    }

    @Override
    public void addErrorReport(ErrorReportSimpDto errorReportSimpDto) {
            ErrorReportDto errorReportDto = new ErrorReportDto();
            errorReportDto.setWo(errorReportSimpDto.getWo());
            errorReportDto.setErrorDes(errorReportSimpDto.getErrorDes());
            errorReportDto.setErrorType(errorReportSimpDto.getErrorType());
            errorReportDto.setPushStatus(1);// 已推送
            errorReportDto.setHandleStatus(0); //待处理
            errorReportDto.setOperator(errorReportSimpDto.getOperator());
            errorReportDto.setHandlingMan(errorReportSimpDto.getHandlingMan());
            errorReportDto.setDeadLine(errorReportSimpDto.getDeadLine());
            errorReportDto.setTaskId(errorReportSimpDto.getTaskId());
            errorReportDto.setPriority(errorReportSimpDto.getPriority());
            errorReportDto.setWorkOrderInforId(errorReportSimpDto.getWorkOrderInforId());


            ProductManufactInfor productManufactInfor = productManufactInforRepository.findProductManufactInforById(errorReportSimpDto.getTaskId());

            errorReportDto.setProductCode(productManufactInfor.getBatchProductCode());
            errorReportDto.setProcessCode(productManufactInfor.getProcessCode());
            errorReportDto.setProcessName(productManufactInfor.getProcessName());
            errorReportDto.setProcessSequence(String.valueOf(productManufactInfor.getSequence()));

            ErrorReport errorReport = errorReportMapper.toEntity(errorReportDto);
            errorReportRepository.save(errorReport);
    }

    @Override
    public void updateErrorReport(ErrorReportDto errorReportDto) {
            ErrorReport errorReport = errorReportMapper.toEntity(errorReportDto);
            errorReport=errorReportRepository.save(errorReport);
            if(errorReport.getHandleTime()==null){
                errorReport.setHandleTime(errorReport.getUpdateTime());
                errorReport=errorReportRepository.save(errorReport);
            }

            //handleStatus=1：已被处理
            int handleStatus = errorReportDto.getHandleStatus();
            if (handleStatus==1){
                //-----------------------------------------------------------------------
                // 异常处理人 发送 异常已处理 待办给  异常申报人
                NotifyInfo notifyInfo =new NotifyInfo();
                notifyInfo.setModuleName("工作平台");
                notifyInfo.setFuncName("异常反馈");
                String projectName2= "-";
                if(errorReport.getProjectName()!=null) projectName2=errorReport.getProjectName();
                String wo = "-";
                if(errorReport.getWo()!=null) wo=errorReport.getWo();


                notifyInfo.setNotifyDesc("项目名称为["+projectName2+"],工单号为["+wo+"],["+errorReport.getErrorType()+"]已被处理--异常已被处理,待确认");
                notifyInfo.setNotifyType("待办");
                notifyInfo.setSenderName(errorReport.getHandlingMan());
                notifyInfo.setSendTime(errorReport.getHandleTime());

                notifyInfo = notifyInfoRepository.save(notifyInfo);

                notifyTemplateInfoService.sendNotify(notifyInfo,-2,errorReport.getOperator(),null);
            }
    }

    @Override
    public void delErrorReport(String id) {
        ErrorReport errorReport = errorReportRepository.findErrorReportById(id);
        errorReport.setDelete(1);
        errorReportRepository.save(errorReport);
    }

    @Override
    public void delErrorReports (List<String> ids) { }

    @Override
    public void deliverErrorReport(ErrorReportDto errorReportDto) {
        ErrorReport errorReport = errorReportRepository.findErrorReportById(errorReportDto.getId());
        errorReport = errorReportMapper.toEntity(errorReportDto);
        errorReportRepository.save(errorReport);
    }

    @Override
    public ArrayList<Integer> getErrorReportProgress() {
        Integer errorReportNumber = errorReportRepository.countErrorReportByDelete(0);
        //已完成的异常数量
        Integer finishedErrorReportNumber = errorReportRepository.countErrorReportByHandleStatusAndDelete(2 , 0);
        Integer number = errorReportNumber - finishedErrorReportNumber;
        ArrayList<Integer> errorReportProgress = new ArrayList<>();
        errorReportProgress.add(0,number);
        return errorReportProgress;
    }

    @Override
    public List<User> getErrorReportMembers() {
        List<User> userList = userRepository.findUsersByDelete(0);
        return userList;
    }

    @Override
    public String getErrorPreviewUrl(ErrorReportDto errorReportDto) throws Exception {
        String fileCode = errorReportDto.getFileCode();
        String fileName = errorReportDto.getFileName();
        String FileName = fileCode+"+"+fileName ;
        String preview_url = minioUtil.getPreviewFileUrl(errorReportDto.getBucketName(),FileName);
        errorReportDto.setAttachmentUrl(preview_url);
        ErrorReport errorReport = errorReportMapper.toEntity(errorReportDto);
        errorReportRepository.save(errorReport);
        return preview_url;
    }

    @Override
    public List<ErrorReportForExportEx> exportErrorReportByHandleStatus(Integer handleStatus) {
        List<ErrorReport> errorReportList=errorReportRepository.findErrorReportByHandleStatusAndDelete(handleStatus,0);
        List<ErrorReportForExportEx> list =new ArrayList<>();
        for(ErrorReport errorReport:errorReportList){
            ErrorReportForExportEx errorReportForExportEx = new ErrorReportForExportEx();
            if(errorReport.getProjectName()!=null)errorReportForExportEx.setProjectName(errorReport.getProjectName());
            if(errorReport.getWo()!=null)errorReportForExportEx.setWo(errorReport.getWo());
            if(errorReport.getWorkHour()!=null)errorReportForExportEx.setWorkHour(errorReport.getWorkHour());
            if(errorReport.getErrorType()!=null)errorReportForExportEx.setErrorType(errorReport.getErrorType());
            if(errorReport.getPriority()!=null){
                DictType dictType = dictTypeRepository.findDictTypeByDictName("异常优先级");
                HashMap<String,String> map = dictDataService.getDictDataMapByDictTypeId(dictType);
                errorReportForExportEx.setPriority(map.get(errorReport.getPriority()));
            }
            if(errorReport.getErrorDes()!=null)errorReportForExportEx.setErrorDes(errorReport.getErrorDes());
            if(errorReport.getDeadLine()!=null)errorReportForExportEx.setDeadLine(errorReport.getDeadLine());
            if(errorReport.getOperator()!=null)errorReportForExportEx.setOperator(errorReport.getOperator());
            if(errorReport.getCreateTime()!=null)errorReportForExportEx.setCreateTime(errorReport.getCreateTime());
            if(errorReport.getHandlingMan()!=null)errorReportForExportEx.setHandlingMan(errorReport.getHandlingMan());
            if(errorReport.getHandleStatus()!=null){
                if (errorReport.getHandleStatus().equals(0)) errorReportForExportEx.setHandleStatusTransfer("待处理");
                if (errorReport.getHandleStatus().equals(1)) errorReportForExportEx.setHandleStatusTransfer("处理中");
                if (errorReport.getHandleStatus().equals(2)) errorReportForExportEx.setHandleStatusTransfer("已完成");
            }
            if(errorReport.getHandleTime()!=null) errorReportForExportEx.setHandleTime(errorReport.getHandleTime());
            if(errorReport.getHandleDes()!=null)errorReportForExportEx.setHandleDes(errorReport.getHandleDes());

            list.add(errorReportForExportEx);
        }

        return list;
    }

    @Override
    public List<ErrorReportForExportEx> exportAllErrorReport() {
        List<ErrorReport> errorReportList=errorReportRepository.findErrorReportByDelete(0);
        List<ErrorReportForExportEx> list =new ArrayList<>();
        for(ErrorReport errorReport:errorReportList){
            ErrorReportForExportEx errorReportForExportEx = new ErrorReportForExportEx();
            if(errorReport.getProjectName()!=null)errorReportForExportEx.setProjectName(errorReport.getProjectName());
            if(errorReport.getWo()!=null)errorReportForExportEx.setWo(errorReport.getWo());
            if(errorReport.getWorkHour()!=null)errorReportForExportEx.setWorkHour(errorReport.getWorkHour());
            if(errorReport.getErrorType()!=null)errorReportForExportEx.setErrorType(errorReport.getErrorType());
            if(errorReport.getPriority()!=null){
                DictType dictType = dictTypeRepository.findDictTypeByDictName("异常优先级");
                HashMap<String,String> map = dictDataService.getDictDataMapByDictTypeId(dictType);
                errorReportForExportEx.setPriority(map.get(errorReport.getPriority()));
            }
            if(errorReport.getErrorDes()!=null)errorReportForExportEx.setErrorDes(errorReport.getErrorDes());
            if(errorReport.getDeadLine()!=null)errorReportForExportEx.setDeadLine(errorReport.getDeadLine());
            if(errorReport.getOperator()!=null)errorReportForExportEx.setOperator(errorReport.getOperator());
            if(errorReport.getCreateTime()!=null)errorReportForExportEx.setCreateTime(errorReport.getCreateTime());
            if(errorReport.getHandlingMan()!=null)errorReportForExportEx.setHandlingMan(errorReport.getHandlingMan());
            if(errorReport.getHandleStatus()!=null){
                if (errorReport.getHandleStatus().equals(0)) errorReportForExportEx.setHandleStatusTransfer("待处理");
                if (errorReport.getHandleStatus().equals(1)) errorReportForExportEx.setHandleStatusTransfer("处理中");
                if (errorReport.getHandleStatus().equals(2)) errorReportForExportEx.setHandleStatusTransfer("已完成");
            }
            if(errorReport.getHandleTime()!=null) errorReportForExportEx.setHandleTime(errorReport.getHandleTime());
            if(errorReport.getHandleDes()!=null)errorReportForExportEx.setHandleDes(errorReport.getHandleDes());

            list.add(errorReportForExportEx);
        }

        return list;
    }

    @Override
    public void finishErrorReport(String id) {
        ErrorReport errorReport = errorReportRepository.findErrorReportById(id);
        errorReport.setHandleStatus(2);
        errorReportRepository.save(errorReport);
    }
}